package com.example.myapplication.ui.accessible

import android.accessibilityservice.AccessibilityService
import android.accessibilityservice.GestureDescription
import android.content.BroadcastReceiver
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import android.util.Log
import android.view.WindowManager
import android.view.accessibility.AccessibilityEvent
import android.view.accessibility.AccessibilityNodeInfo
import android.view.animation.AccelerateInterpolator
import androidx.annotation.RequiresApi
import java.util.Timer
import java.util.TimerTask

class SmartFingerService : AccessibilityService() {

    private val handler = Handler(Looper.getMainLooper())

    // 滑动间隔时间
    private val scrollInterval = 5000L

    // 屏幕宽高
    private var x = 750;
    private var y = 1200;

    // 滑动次数
    private var executeIndex = 0

    private var customReceiver: BroadcastReceiver? = null
    val customEvent = "com.example.action.CUSTOM_TIMED_TASK_SWIPE"

    /**
     * 获取屏幕宽高包含顶部状态栏，底部导航栏
     */
    @RequiresApi(Build.VERSION_CODES.R)
    fun getScreenSize() {
        try {
            val windowManager = getSystemService(WINDOW_SERVICE) as WindowManager
            val windowMetrics = windowManager.currentWindowMetrics
            val bounds = windowMetrics.bounds
            x = bounds.width()
            y = bounds.height()
        } catch (e: Exception) {
            // 异常回退（例如旧设备使用 getMetrics）
            val displayMetrics = resources.displayMetrics
            Pair(displayMetrics.widthPixels, displayMetrics.heightPixels)
        }
    }

    @RequiresApi(Build.VERSION_CODES.R)
    override fun onCreate() {
        super.onCreate()
        Log.d("SmartFingerService", "注册广播接收器")

        // 初始化屏幕宽高
        getScreenSize()

        // 动态注册广播接收器(函数式接口)
        customReceiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {
                if (intent?.action == customEvent) {
                    // 获取广播数据
                    val command = intent.getStringExtra("customType")
                    Log.d("SmartFingerService", "接收到的参数")
                    Log.d("SmartFingerService", command.toString())

                    if (command == "start") {
                        Log.d("SmartFingerService", "开始滑动")
                        // 开始滑动
                        setTimeout(2000) {
                            Log.d("SmartFingerService", "延时器启动")
                            startAuto()
                        }
                    } else if (command == "end") {
                        Log.d("SmartFingerService", "停止滑动")
                        // 停止滑动
                        endAuto()
                    } else if (command == "simulateClick") {
                        Log.d("SmartFingerService", "模拟点击")

                        simulateClick(20, 533)
                    } else {
                        Log.d("SmartFingerService", "未识别操作")
                    }
                }
            }
        }

        // 注册接收器（使用自定义 Action）
        registerReceiver(
            customReceiver,
            IntentFilter(customEvent),
            Context.RECEIVER_NOT_EXPORTED
        )
    }

    // 检查是否启用无障碍模式
    private fun isAccessibilityServiceEnabled(): Boolean {
        val serviceName = ComponentName(this, SmartFingerService::class.java)
        val enabledServices = Settings.Secure.getString(
            contentResolver,
            Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES
        )
        return enabledServices?.contains(serviceName.flattenToString()) ?: false
    }

    /**
     * 自动填入文字
     */
    private fun inputText(node: AccessibilityNodeInfo, text: String) {
        // 方式1：直接设置文本（API 21+）
        val args = Bundle().apply {
            putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, text)
        }
        node.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, args)
    }

    override fun onAccessibilityEvent(event: AccessibilityEvent?) {
        if (isAccessibilityServiceEnabled()) {
            Log.d("SmartFingerService", "无障碍服务已开启")
            if (event?.eventType == AccessibilityEvent.TYPE_VIEW_FOCUSED) {
                // 元素获取焦点后的操作
                Log.d("SmartFingerService", "获取焦点")

                val focusedNode = event.source;

                if (focusedNode != null) {
                    setTimeout(2000) {
                        inputText(focusedNode, "自动填入的文字")
                    }
                }

            } else if (event?.eventType == AccessibilityEvent.TYPE_VIEW_CLICKED) {
                // 元素被点击后的操作
                Log.d("SmartFingerService", "点击")
                println(event)
            } else {
                Log.d("SmartFingerService", "未知操作")
            }
        } else {
            Log.d("SmartFingerService", "未开启无障碍服务")
        }
    }

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    override fun onServiceConnected() {
        super.onServiceConnected()
    }

    override fun onInterrupt() {
        TODO("Not yet implemented")
    }

    override fun onDestroy() {
        super.onDestroy()
        customReceiver?.let { unregisterReceiver(it) }
    }

    // 开始执行定时器
    fun startAuto() {
        Log.d("SmartFingerService", "开始执行任务")

        // 根据参数做不通概率的操作

        // 1.滑动多少次自动结束任务
        // 2.点赞的概率
        // 3.打开评论区浏览评论的概率
        // 4.自动评论的概率
        // 5.所有的操作在执行之前都已经确定好了，并确定了这个任务的执行时间何时开始执行下一次操作


//        simulateSwipe((x / 2), (y / 4), (y / 2))
        handler.postDelayed(scrollRunnable, scrollInterval)
    }

    // 结束定时任务
    fun endAuto() {
        executeIndex = 0
        handler.removeCallbacks(scrollRunnable)
    }

    private val scrollRunnable = object : Runnable {
        override fun run() {
            Log.d("SmartFingerService", "即将开始调用")
            simulateSwipe((x / 2), (y / 4 * 3), (y / 4))
            handler.postDelayed(this, scrollInterval)
        }
    }

    // 模拟 setTimeOut 方法
    private fun setTimeout(delayMillis: Long, callback: () -> Unit): TimerTask {
        val timer = Timer()
        val task = object : TimerTask() {
            override fun run() {
                callback()
                timer.cancel() // 避免内存泄漏
            }
        }
        timer.schedule(task, delayMillis)
        return task
    }

    /**
     * 模拟用户点击
     */
    private fun simulateClick(x: Int, y: Int) {
        val path = android.graphics.Path().apply {
            moveTo(x.toFloat(), y.toFloat())
        }
        val gesture = GestureDescription.Builder()
            .addStroke(GestureDescription.StrokeDescription(path, 50L, 100L)) // 50ms点击持续时间
            .build()

        dispatchGesture(gesture, null, null) // 触发点击
    }

    /**
     * 模拟用户向上滑动(带加速曲线)
     */
    private fun simulateSwipe(startX: Int, startY: Int, endY: Int) {
        executeIndex += 1

        Log.d("SmartFingerService", executeIndex.toString())

        val durationMs = 600L // 滑动时间
//        val steps = 20 // 分割步骤书
//        val interpolator = AccelerateInterpolator(1.2f)  // 加速强度

        val gestureBuilder = GestureDescription.Builder()

        var currentTimeMs = 0L

        val path = android.graphics.Path().apply {
            moveTo(startX.toFloat(), startY.toFloat())
            lineTo(startX.toFloat(), endY.toFloat())
        }

        gestureBuilder.addStroke(
            GestureDescription.StrokeDescription(
                path,
                currentTimeMs,
                durationMs
            )
        )

        dispatchGesture(gestureBuilder.build(), null, null)
    }

}